package com.carbon.system.service.impl;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.carbon.system.entity.CarbonArticle;
import com.carbon.system.entity.FeishuConfig;
import com.carbon.system.mapper.CarbonArticleMapper;
import com.carbon.system.param.CarbonArticleStatuParam;
import com.carbon.system.service.CarbonArticleService;
import com.carbon.system.param.CarbonArticleQueryParam;
import com.carbon.system.util.CommonUtil;
import com.carbon.common.service.BaseServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.baomidou.mybatisplus.core.metadata.IPage;
import org.springframework.web.multipart.MultipartFile;

import java.util.*;

import static cn.hutool.http.Method.PATCH;


/**
 * <p>
 * 碳文章 服务实现类
 * </p>
 *
 * @author Li Jun
 * @since 2021-08-01
 */
@Slf4j
@Service
@Transactional(rollbackFor = Exception.class)
public class CarbonArticleServiceImpl extends BaseServiceImpl<CarbonArticleMapper, CarbonArticle> implements CarbonArticleService {
    @Autowired
    private CarbonArticleMapper carbonArticleMapper;


    private final FeishuConfig feishuConfig;

    public CarbonArticleServiceImpl(FeishuConfig feishuConfig) {
        this.feishuConfig = feishuConfig;
    }

    @Override
    public IPage<CarbonArticle> search(Page<CarbonArticle> page, CarbonArticleQueryParam param) {
        return carbonArticleMapper.search(page,param);
    }

    @Override
    public Boolean offlineOrUpdate(CarbonArticleStatuParam param) {
        return carbonArticleMapper.offlineOrUpdate(param);
    }




    /**
     * 1. 创建飞书文档并关联业务文章
     */
    @Transactional @Override
    public String createFeishuDoc() {
        // 1. 获取飞书 tenant_token
        String tenantToken = CommonUtil.getTenantToken();
        System.out.println(tenantToken);
        // 2. 调用飞书创建文档接口
        Map<String, Object> reqBody = new HashMap<>();
        reqBody.put("FolderToken", ""); // 文件夹 token，空表示根目录（按需调整）
        reqBody.put("Content", ""); // 文档初始内容（按需填充，支持富文本格式）

        String res = HttpUtil.createPost("https://open.feishu.cn/open-apis/docx/v1/documents")
                .header("Authorization",  tenantToken)
                .header("Content-Type", "application/json; charset=utf-8")
                .body(JSONUtil.toJsonStr(reqBody))
                .execute().body();

        JSONObject resultJson = JSONUtil.parseObj(res);
        if (resultJson.getInt("code") != 0) {
            throw new RuntimeException("飞书文档创建失败：" + res);
        }
        Map<String, Object> resultMap = JSON.parseObject(String.valueOf(resultJson), Map.class);
        // 3. 解析飞书返回的文档 URL
        Map<String, Object> dataMap = (Map<String, Object>) resultMap.get("data");
        Map<String, Object> docMap = (Map<String, Object>) dataMap.get("document");
        String documentId = (String) docMap.get("document_id");
        String permissionUrl = "https://open.feishu.cn/open-apis/drive/v2/permissions/" + documentId + "/public?type=docx";
        Map<String, Object> permissionBody = new HashMap<>();
        permissionBody.put("link_share_entity", "tenant_editable");

        // 直接构造HTTP请求，指定方法为PATCH
        HttpRequest permissionRequest = HttpUtil.createRequest(PATCH, permissionUrl)
                .header("Authorization", tenantToken)
                .header("Content-Type", "application/json; charset=utf-8")
                .body(JSONUtil.toJsonStr(permissionBody));
        String permissionRes = permissionRequest.execute().body();

        JSONObject permissionResult = JSONUtil.parseObj(permissionRes);
        if (permissionResult.getInt("code") != 0) {
            throw new RuntimeException("设置文档权限失败：" + permissionRes);
        }
        CarbonArticle article = new CarbonArticle();
        article.setUrl("https://feishu.cn/docx/"+documentId);
        article.setStatus("0260000004");
        // 其他字段可后续同步时填充，这里先保存 URL
        carbonArticleMapper.saveFeishuDocInfo(article);

        // 4. 返回给前端编辑链接
        return ("https://feishu.cn/docx/"+documentId);
    }

    /**
     * 2. 同步飞书文档内容到业务数据库
     */
    /**
     * 2. 同步飞书文档内容到业务数据库
     */
    @Transactional
    @Override
    public void syncFeishuDoc(String accessToken) {
        // 1. 从数据库获取飞书文档 URL（题目为空的文档）
        List<String> docUrls = carbonArticleMapper.getFeishuDocUrl();

        if (docUrls == null || docUrls.isEmpty()) {
            log.info("没有需要同步的飞书文档");
            return;
        }

        // 2. 解析 docTokens
        List<String> docTokens = new ArrayList<>();
        Map<String, String> tokenToUrlMap = new HashMap<>();

        for (String docUrl : docUrls) {
            String docToken = CommonUtil.parseDocTokenFromUrl(docUrl);
            if (docToken != null && !docToken.isEmpty()) {
                docTokens.add(docToken);
                tokenToUrlMap.put(docToken, docUrl);
            }
        }

        if (docTokens.isEmpty()) {
            log.warn("没有有效的文档token需要同步");
            return;
        }

        //String tenantToken = CommonUtil.getTenantToken();

        // 3. 批量获取文档元数据
        try {
            // 构造批量查询请求体
            Map<String, Object> batchReqBody = new HashMap<>();
            List<Map<String, String>> requestDocs = new ArrayList<>();
            for (String docToken : docTokens) {
                Map<String, String> docInfo = new HashMap<>();
                docInfo.put("doc_token", docToken);  // 文档唯一标识
                docInfo.put("doc_type", "docx");     // 文档类型，新版文档固定为 "docx"
                requestDocs.add(docInfo);
            }
            batchReqBody.put("request_docs", requestDocs);

//            String batchMetaRes = HttpUtil.createPost("https://open.feishu.cn/open-apis/drive/v1/metas/batch_query")
//                    .header("Authorization", tenantToken)
//                    .header("Content-Type", "application/json; charset=utf-8")
//                    .body(JSONUtil.toJsonStr(batchReqBody))
//                    .execute().body();
            String batchMetaRes = HttpUtil.createPost("https://open.feishu.cn/open-apis/drive/v1/metas/batch_query?user_id_type=open_id")
                    .header("Authorization", "Bearer " + accessToken)  // 确保token前有"Bearer "前缀
                    .header("Content-Type", "application/json; charset=utf-8")
                    .body(JSONUtil.toJsonStr(batchReqBody))
                    .execute().body();
            if (batchMetaRes == null || batchMetaRes.trim().isEmpty()) {
                log.error("获取飞书文档元数据失败：响应为空");
                return;
            }

            String trimmedBatchMetaRes = batchMetaRes.trim();
            if (!trimmedBatchMetaRes.startsWith("{")) {
                log.error("获取飞书文档元数据失败：响应不是有效的JSON格式，响应内容: {}", batchMetaRes);
                return;
            }

            JSONObject batchMetaJson;
            try {
                batchMetaJson = JSONUtil.parseObj(trimmedBatchMetaRes);
            } catch (Exception e) {
                log.error("解析飞书文档元数据JSON失败：{}", batchMetaRes, e);
                return;
            }

            int code = batchMetaJson.getInt("code");
            if (code != 0) {
                String errorMsg = batchMetaJson.getStr("msg", "未知错误");
                log.error("获取飞书文档元数据失败，错误码: {}，错误信息: {}，响应: {}", code, errorMsg, batchMetaRes);
                throw new RuntimeException("获取飞书文档元数据失败：" + errorMsg);
            }

            // 4. 处理返回的文档元数据
            JSONObject data = batchMetaJson.getJSONObject("data");
            if (data != null) {
                // 使用正确的Hutool方法获取数组
                cn.hutool.json.JSONArray metasArray = data.getJSONArray("metas");
                if (metasArray != null && !metasArray.isEmpty()) {
                    for (int j = 0; j < metasArray.size(); j++) {
                        try {
                            JSONObject docMeta = metasArray.getJSONObject(j);
                            String token = docMeta.getStr("doc_token");
                            String title = docMeta.getStr("title");
                            String url = tokenToUrlMap.get(token);

                            if (token != null && url != null) {
                                // 5. 获取文档内容（如果需要）
                                String content = fetchDocumentContent(token, accessToken);
                                String modifyUserId = docMeta.getStr("latest_modify_user");
                                String userName = getUserRealName(modifyUserId, accessToken); // 新增方法

                                // 6. 组装数据并更新业务数据库
                                CarbonArticle article = new CarbonArticle();
                                article.setTitle(title);
                                article.setAuthor(userName);
                                article.setContent(content);
                                article.setStatus("0260000001"); // 状态码按需调整
                                article.setUrl(url);

                                carbonArticleMapper.updateFeishuDocContent(article);
                                log.info("成功同步文档: {} - {}", token, title);
                            }
                        } catch (Exception e) {
                            log.error("处理单个文档元数据时出错: {}", e);
                        }
                    }
                }
            }
        } catch (Exception e) {
            log.error("同步飞书文档过程中发生错误", e);
            throw new RuntimeException("同步飞书文档失败：" + e.getMessage());
        }
    }

    // 新增的用户信息查询方法
    private String getUserRealName(String openId, String tenantToken) {
        String userInfoUrl = "https://open.feishu.cn/open-apis/contact/v3/users/" + openId + "?user_id_type=open_id";
        String userInfoRes = HttpUtil.createGet(userInfoUrl)
                .header("Authorization", "Bearer "+tenantToken)
                .execute().body();
        JSONObject userJson = JSONUtil.parseObj(userInfoRes);
        Map<String, Object> userMap = userJson.getJSONObject("data")
                .getJSONObject("user")
                .toBean(Map.class);

        if (userJson.getInt("code") == 0) {
            return  (String) userMap.get("name");

        }
        return openId; // 失败时返回原始ID
    }
    /**
     * 获取单个文档内容
     */
    private String fetchDocumentContent(String docToken, String tenantToken) {
        try {
            // 对于docx文档，可以使用不同的API获取内容
            String contentUrl = "https://open.feishu.cn/open-apis/docx/v1/documents/" + docToken + "/raw_content";

            String contentRes = HttpUtil.createGet(contentUrl)
                    .header("Authorization", "Bearer " + tenantToken)
                    .execute().body();

            if (contentRes != null && contentRes.trim().startsWith("{")) {
                JSONObject contentJson = JSONUtil.parseObj(contentRes);
                if (contentJson.getInt("code") == 0) {
                    cn.hutool.json.JSONObject dataObj = contentJson.getJSONObject("data");
// 再从 data 里拿到 content 字段的字符串
                    String content = dataObj.getStr("content");
                    return content;
                } else {
                    log.warn("获取文档内容失败，token: {}，响应: {}", docToken, contentRes);
                }
            }
        } catch (Exception e) {
            log.error("获取文档内容时出错，token: {}", docToken, e);
        }
        return ""; // 返回空内容而不是null
    }

}